<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>响应式</title>
</head>

<body>
    <script>
        let bucket = new WeakMap()
        let activeEffect

        function effect(fn) {
            activeEffect = fn
            fn()
        }

        function effect(fn) {
            const effectFn = () => {
                cleanup(effectFn)
                activeEffect = effectFn
                fn()
            }
            effectFn.set = []
            effectFn()
        }

        function cleanup(effectFn) {
            for (let i = 0; i < effectFn.set.length; i++) {
                const set = effectFn.set[i]
                set.delete(effectFn)
            }
            effectFn.set.length = 0
        }

        function track(target, key) {
            if (!activeEffect) return
            let map = bucket.get(target)
            if (!map) {
                map = new Map()
                bucket.set(target, map)
            }
            let set = map.get(key)
            if (!set) {
                set = new Set()
                map.set(key, set)
            }
            set.add(activeEffect)
            activeEffect.set.push(set)
        }

        function trigger(target, key) {
            const map = bucket.get(target)
            if (!map) return
            const effects = map.get(key)
            const effectsToRun = new Set(effects)
            effectsToRun.forEach(effectFn => effectFn())
        }

        const data = {
            text: '123',
            ok: true
        }

        const obj = new Proxy(data, {
            get(target, key) {
                track(target, key)
                return target[key]
            },
            set(target, key, value) {
                target[key] = value
                trigger(target, key)
            }
        })

        effect(() => {
            console.log('副作用函数执行了')
            document.body.innerText = obj.ok ? obj.text : 'not'
        })

        obj.ok = false
        obj.text = '456'
        obj.text = '789'

    </script>
</body>

</html>